package org.shean.app.rssreader.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

// Single-byte: 0x00-0x7f
// Two-byte:    [0x81-0xfe] + [0x40-0x7e, 0x80-0xfe]
// Four-byte:   [0x81-0xfe] + [0x30-0x39] + [0x81-0xfe] + [0x30-0x39]

public class GBKTable {
   // data[0] = unicode for GBK(0x8140)
   // each row is [0x40~0xff] = 192 bytes wide
   // 4-byte encoding is not supported
    public static char data[];

    public static final int START_ROW = 0x81;
    public static final int END_ROW   = 0xff; // inclusive
    public static final int START_COL = 0x40;
    public static final int END_COL   = 0xff; // inclusive

    public static void init(byte[] buffer) {
        int i = 0, j = 0;
        int size = (END_ROW - START_ROW + 1) * (END_COL - START_COL + 1);
        data = new char[size];

        for (int r = START_ROW ; r <= END_ROW; r++) {
            for (int c = START_COL ; c <= END_COL; c++) {
                int lo = buffer[i++]; // Input is little endian 16-bit UNICODE
                int hi = buffer[i++];
                int chr = (hi << 8) | (lo & 0xff);
                data[j++] = (char)chr;      // No need to mask off high 16 bit. It will be truncated.
            }
        }
    }

    public static boolean isInited() {
        return (data != null);
    }
    
    public static boolean isGBKUrl(String urlstr)
	{
		boolean res = false;
		try{
			URL url = new URL(urlstr);
			URLConnection connection = url.openConnection();
			connection.setConnectTimeout(10000);
			connection.setReadTimeout(10000);
			connection.connect();
			InputStream in = connection.getInputStream();
			
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			
			String head = br.readLine().toLowerCase();
			
			if(head.contains("gbk") || head.contains("gb2312"))
				res = true;
			
			in.close();
		}
		catch(Exception e)
		{
			
		}
		
		return res;
		
	}
}
